package com.binance.rabbitmq.recoverer.impl;

import com.binance.rabbitmq.recoverer.MessageExceptionHandler;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by robin.wu on 2018/11/29.
 */
@Log4j2
public class LogMessageExceptionHandler implements MessageExceptionHandler {
    private static List directlyReadableContentTypes;

    static{

        List tmpDirectlyReadableContentTypes = Arrays.asList("text/plain",
                "application/json",
                "text/x-json",
                "application/xml");

        directlyReadableContentTypes= Collections.unmodifiableList(tmpDirectlyReadableContentTypes);

    }

    @Override
    public void handle(Message message, Throwable cause) {
        Map<String, Object> headers = message.getMessageProperties().getHeaders();
        log.warn("Exception occurred while processing the message from queue {{}} , message {{}} , headers {{}} :  cause",
                headers.get("x-original-queue"), getMessageString(message), headers, cause);
    }

    protected String getMessageString(Message message) {
        String contentType = message.getMessageProperties() != null ? message.getMessageProperties().getContentType() : null;

        if (directlyReadableContentTypes.contains(contentType)) {
            return new String(message.getBody());
        } else {
            return Arrays.toString(message.getBody()) + "(byte[" + message.getBody().length + "])";
        }
    }
}
